package yartiss.engine.simulation.scheduling.policies.fp;

import java.util.SortedSet;

import yartiss.engine.simulation.IEnergyProfile;
import yartiss.engine.simulation.ISchedulingPolicy;
import yartiss.engine.simulation.events.EventGenerator;
import yartiss.engine.simulation.scheduling.policies.AbstractMonoProcessorSchedulingPolicy;
import yartiss.engine.simulation.system.ITask;
import yartiss.engine.simulation.system.ITaskSet;
import yartiss.engine.simulation.system.taskset.TaskSetFactory;

public class FPSchedulingPolicy extends AbstractMonoProcessorSchedulingPolicy {

	@Override
	public String getPolicyName() {
		return "FP";
	}

	@Override
	public ITaskSet createTaskSet() {
		return TaskSetFactory.getNewInstance("priority");
	}
	
	@Override
	public ISchedulingPolicy newInstance() {
		return new FPSchedulingPolicy();
	}

	@Override
	public ITask chooseNextTask(ITaskSet taskSet, IEnergyProfile energyProfile,	long date, EventGenerator evGen) {
		SortedSet<ITask> activeTasks = taskSet.getActiveTasks(date);
		
		if(!activeTasks.isEmpty()){
			ITask first = activeTasks.first();
			long hlcet = energyProfile.howLongCanExecute(first);
			if (hlcet <= 0) {
				evGen.generateEvent("energy_failure", activeTasks.first(), date, null);
				return null;
			}

			if (hlcet < activeTasks.first().getRemainingCost())
				evGen.generateEvent("check_energy_state", activeTasks.first(), date + hlcet, null);
			
			return activeTasks.first();
		}
			
		return  null;
	}
}
